package com.ezops.gateway;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import com.ezops.filter.ReportCriteria;
import com.ezops.service.IReportLocatorService;
import com.ezops.util.ApplicationContextUtils;
import com.ezops.util.Report;

/**
 * Default report response handler. The default handling is to save the report
 * on the disk. This class is responsible for persisting the object (csv ) on to
 * the disk.
 * 
 * @author vgaurav
 * 
 */
public class DefaultReportCallBackHandler implements ResponseHandler {

	private String messageKey;
	private CountDownLatch latch = new CountDownLatch(1);
	private ReportCriteria reportCriteria;

	public DefaultReportCallBackHandler(ReportCriteria criteria) {
		reportCriteria = criteria;
	}

	/**
	 * Save the reponse to the disk as CSV file.
	 */
	@Override
	public void handle(Object response) {
		Reader messagereader = new StringReader(response.toString());
		try {
			Report report = new Report(messagereader);
			IReportLocatorService locator = ApplicationContextUtils.getContext().getBean(IReportLocatorService.class);
			report.save(locator.locate(reportCriteria));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			latch.countDown();
		}

	}

	public boolean isReponseReceived() {
		try {
			latch.await(60000, TimeUnit.MILLISECONDS);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public String getMessageIdentifierKey() {
		return messageKey;
	}

	@Override
	public void setMessageIdentifierKey(String identifier) {
		this.messageKey = identifier;
	}
}
